package com.air.listeners;

import com.air.tools.StringTools;
import com.air.tools.TaskFather;
import com.air.tools.output;
import com.air.ui.MainWindow;
import com.alibaba.fastjson.JSON;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * 开始搜索按钮监听
 */
public class StartSearchListener implements ActionListener {
    @Override
    public void actionPerformed(ActionEvent e) {
        String input = mw.getTextField_SearchText().getText();
        if (StringTools.isEmptyWithTrimOrNull(input)) {
            return;
        }
        mw.getBtn_Start().setEnabled(false);
        mw.getBtn_Stop().setEnabled(true);
        total = 0;
        finashTotal = 0;
        new Thread(() -> {
            taskFather = new TaskFather(mw, this);
            taskFather.start();
        }).start();
    }

    public StartSearchListener(MainWindow mw) {
        this.mw = mw;
    }

    public synchronized void addFinalsh(TaskFather taskFather) {
        ++finashTotal;
        if (finashTotal < total) {
            mw.setTitle(mw.getTitleStr() + "     搜索中... ");
        } else {
            allFinalsh(null);

            output.outLine("一共表列：" + taskFather.getResults().size());
            output.outLine("JSON: \n\n\n");
            output.outLine(JSON.toJSONString(taskFather.getResults()));
        }
    }

    /**
     * 全部完成 刷新界面
     */
    public void allFinalsh(String info) {
        if (StringTools.isEmptyWithTrimOrNull(info)) {
            mw.setTitle(mw.getTitleStr() + "     搜索完成!  100%");
        } else {
            mw.setTitle(mw.getTitleStr() + info);
        }
        output.outLine("所有线程已完成, 搜索完成! ");
        mw.getBtn_Start().setEnabled(true);
        mw.getBtn_Stop().setEnabled(false);
    }

    public void setTotal(int total) {
        this.total = total;
    }

    public void stop() {
        taskFather.stopAll();
    }

    private int total = 0;
    private int finashTotal = 0;
    private MainWindow mw;
    private TaskFather taskFather;
}
